package com.example.steeringwheelseekbar

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.Rect
import android.util.AttributeSet
import android.view.View

/**
 * 自定义SeekBar 前景部分
 */
class SeekBarForegroundView : View {
    private var paint: Paint? = null
    private var foregroundSize = 0
    private var foreground = 0
    private var bitmapPaint: Bitmap? = null
    private var src: Rect? = null
    private var dst: Rect? = null

    // Matrix类进行图片处理（缩小或者旋转）
    private val matrix = Matrix()
    private var deg = 0f

    constructor(context: Context, foregroundSize: Int, foreground: Int) : super(context) {
        this.foregroundSize = foregroundSize
        this.foreground = foreground
        init()
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        foregroundSize = 10
        foreground = 0
        init()
    }

    private fun init() {
        paint = Paint()
        //设置抗锯齿,防止过多的失真
        paint!!.isAntiAlias = true
        if (foreground != 0) {
            bitmapPaint = BitmapFactory.decodeResource(this.resources, foreground)
            val tempBitmapPaint = bitmapPaint
            // 指定图片绘制区域(原图大小)
            if (tempBitmapPaint != null) {
                src = Rect(0, 0, tempBitmapPaint.getWidth(), tempBitmapPaint.getHeight())
            }
            // 指定图片在屏幕上显示的区域(ballSize大小)
            dst = Rect(0, 0, foregroundSize, foregroundSize)
        }
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val spec = MeasureSpec.makeMeasureSpec(foregroundSize, MeasureSpec.EXACTLY)
        setMeasuredDimension(spec, spec)
    }

    override fun onDraw(canvas: Canvas) {
        if (foreground == 0) {
            canvas.drawCircle(
                measuredWidth.toFloat() / 2,
                measuredWidth.toFloat() / 2,
                measuredWidth.toFloat() / 2,
                paint!!
            )
        } else {
            // 旋转
            matrix.setRotate(deg % 360, foregroundSize.toFloat() / 2, foregroundSize.toFloat() / 2)
            canvas.setMatrix(matrix)
            canvas.drawBitmap(bitmapPaint!!, src, dst!!, paint)
        }
    }

    /**
     * @param degrees 旋转角度
     */
    fun setDegrees(degrees: Float) {
        deg = degrees
        postInvalidate()
    }
}